package APIs.twitter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;

import twitter4j.*;
import twitter4j.auth.*;

public class OAuthMain {

	
	public static boolean updateExistingUser(String username,String update) throws Exception{
		String[] keys = loadKeys(username); //  first we load our keys
		// make sure we have a generated user
		if(keys[3].compareTo("") == 0 || keys[2].compareTo("") == 0) {
			throw new Exception("EPIC FAIL ERROR: User does not exist in keys file!!!");
		}
					
		TwitterFactory factory = new TwitterFactory();
		AccessToken accessToken = new AccessToken(keys[2],keys[3]); // generate our access token
		Twitter twitter = factory.getInstance();
		twitter.setOAuthConsumer(keys[0], keys[1]); // consumer key, consumer secret
		twitter.setOAuthAccessToken(accessToken);
		Status status = twitter.updateStatus(update);
		System.out.println("Successfully updated the status to [" + status.getText() + "].");
		
		return true;
	}
	
	public static boolean generateNewUserTokens() throws Exception{
		String[] keys = loadKeys(""); // 0 = consumer key, 1 = consumer secret, 2 = user access token, 3 = user secret token
		Twitter twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(keys[0], keys[1]);
		RequestToken requestToken = twitter.getOAuthRequestToken();
		AccessToken accessToken = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (null == accessToken) {
			System.out.println("Open the following URL and grant access to your account:");
			System.out.println(requestToken.getAuthorizationURL());
			System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
			String pin = br.readLine();
			try{
				if(pin.length() > 0){
					accessToken = twitter.getOAuthAccessToken(requestToken, pin);
				}else{
					accessToken = twitter.getOAuthAccessToken();
				}
			} catch (TwitterException te) {
				if(401 == te.getStatusCode()){
					System.out.println("Unable to get the access token.");
				}else{
					te.printStackTrace();
				}
			}
		}
		
		System.out.println("Username: " + twitter.getScreenName());
		System.out.println("Access token: " + accessToken.getToken());
		System.out.println("Secret Access Token: " + accessToken.getTokenSecret());
		
		return true;
	}
	
	public static String[] loadKeys(String username){
		String[] keys = new String[4]; // this stores the keys we will return
		boolean firstTime = true;
		boolean notFound = true;
		String buf = ""; // this is our read buffer
		
		// zero our key array out
		for(int i = 0; i < keys.length; i++) {
			keys[i] = "";
		}
		
		try {
			BufferedReader inFile = new BufferedReader(new FileReader("keys.txt"));
			// write our image name out to the file
			while(inFile.ready() && notFound) {
				if(firstTime) {
					buf = inFile.readLine(); // read the first line
					keys[0] = buf.split(" ")[0]; // consumer key stored here
					keys[1] = buf.split(" ")[1]; // consumer secret stored here
					firstTime = false; // make sure we dont do this again
				} else {
					buf = inFile.readLine(); // read a line
					
					// check if we are dealing with the correct user
					if(buf.split(" ")[0].compareTo(username) == 0) {
						// if we got here, we are dealing with the correct user
						keys[2] = buf.split(" ")[1]; // save the user access token
						keys[3] = buf.split(" ")[2]; // save the user secret token
					}
				}
			}
				
			// close the file
			inFile.close();
		} catch (Exception e) {
			// if we dont have a file, this will catch the no file error and still return an empty buffer
			e.printStackTrace();
		}
		
		return keys;
	}

	
}
